{% load static %}
{# bootstrap #}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
{# amap api #}
<link rel="stylesheet" type="text/css" href="{% static 'visualization/on_map.css' %}"/>
<script type="text/javascript"
        src="https://webapi.amap.com/maps?v=1.4.15&key=f8188c8ddd28b384b3a636476a6540e5&plugin=AMap.MouseTool">
</script>
{# customize #}
<script type="text/javascript" src="{% static 'visualization/map_draw.js' %}"></script>
<style type="text/css">
    .top-buffer {
        margin-top: 5px;
    }

    .left-buffer {
        margin-left: 5px;
    }

    .canvas_of_picture {
        float: left;
    }
</style>

<div id="container"></div>

<div class="info" id="main-dash">
    <form action="{% url 'uccsit:index' %}" method="post">
        {% csrf_token %}
        <h3 align="center">泊车数据可视化</h3>
        <div class="row justify-content-md-center">
            {#            <div class="col-auto">#}
            {#                <h5>时间：</h5>#}
            {#            </div>#}
            <div class="col-auto">
                <input type='text' name="datetime" class="form-control" value="{{ datetime }}"/>
                <small id="passwordHelpBlock" class="form-text text-muted">
                    有效时间：2018-9-1 ~ 2018-9-7
                </small>
            </div>
            <div class="col-auto">
                <button type="submit" class="col-sm btn btn-primary left-buffer">更改</button>
            </div>
        </div>
    </form>
    <div class="btn-group btn-group-toggle btn-block" data-toggle="buttons">
        <label class="btn btn-secondary active" onClick="show(1)">
            <input type="radio" name="options" id="option1" autocomplete="off" checked> 用量排行
        </label>
        <label class="btn btn-secondary" onclick="show(2)">
            <input type="radio" name="options" id="option2" autocomplete="off"> 空闲排行
        </label>
    </div>
    <div id="sorted_occupancy"></div>

</div>
<div class="info" id="canvas_of_vote">
    <div class="canvas_of_picture">
        <div class="btn-group btn-group-toggle col-xl" data-toggle="buttons">
            <label class="btn btn-outline-secondary" onClick="draw_aggregate_rates('day')">
                <input type="radio" name="aggregate_scale" id="option1" autocomplete="off" checked>
                日
            </label>
            <label class="btn btn-outline-secondary active" onClick="draw_aggregate_rates('week')">
                <input type="radio" name="aggregate_scale" id="option2" autocomplete="off">
                周
            </label>
            <label class="btn btn-outline-secondary" onClick="draw_aggregate_rates('avg')">
                <input type="radio" name="aggregate_scale" id="option3" autocomplete="off">
                周平均
            </label>
        </div>
        <div id="canvas_aggregate_rate"></div>
    </div>
    <div class="canvas_of_picture">
        <div class="canvas_of_picture">
            <div class="btn-group btn-group-toggle col-xl" data-toggle="buttons">
                <label class="btn btn-outline-secondary" onClick="draw_block_rate('day')">
                    <input type="radio" name="options" id="option1" autocomplete="off" checked>
                    日
                </label>
                <label class="btn btn-outline-secondary" onClick="draw_block_rate('week')">
                    <input type="radio" name="options" id="option2" autocomplete="off">
                    周
                </label>
                <label class="btn btn-outline-secondary active" onClick="draw_block_rate('avg')">
                    <input type="radio" name="options" id="option3" autocomplete="off">
                    周平均
                </label>
            </div>
            <div id="canvas_block_rate"></div>
        </div>
        <div class="canvas_of_picture" id="canvas_block_bcu"></div>
    </div>
    <div id="summary-dash"></div>
    <div id="summary-pie" align="center"></div>
</div>

<script type="text/javascript">
    var map = new AMap.Map('container', {
        expandZoomRange: true,
        zoom: 16,//级别
        zooms: [3, 20],
        center: [113.935197, 22.51659],//中心点坐标
        features: ['bg', 'road', 'building'],
        showLabel: true
    });
    {# info of blocks #}
    var block_location = [];
    var block_capacity = [];
    var block_used = [];
    {# statistical data of blocks #}
    var all_block = 0;
    var congestion_block = 0;
    var underuse_block = 0;
    var balance_block = 0;
    var all_berth = 0;
    {# info of selected road #}
    var block_id = 35;
    var road_name = '海德二道';
    var left_or_right = '靠右';
    var direction = '南侧';
    var block_scale = 'avg';
    {% for block_id, info in block_info %}
        block_capacity[{{ block_id }}] = {{ info.capacity }};
        block_used[{{ block_id }}] = {{ info.used_count }};
        {% for shape in info.shape %}
            block_location[{{ block_id }}] ={{ shape }};
            var polyline = new AMap.Polyline({
                path: {{ shape }},
                bubble: true,
                borderWeight: 1, // 线条宽度，默认为 1
                strokeWeight: 3,
                strokeColor: '{{ info.color }}', // 线条颜色
                lineJoin: 'round', // 折线拐点连接处样式
                extData: '{{ block_id }}',
            });
            polyline.on('mouseover', function (ev) {
                ev.target.setOptions({
                    strokeWeight: 7,
                });
            });
            polyline.on('mouseout', function (ev) {
                ev.target.setOptions({
                    strokeWeight: 3,
                });
            });
            polyline.on('click', function (ev) {
                var content = ['{{ block_id }}, {{ info.road_name }}, {{ info.direction }}',
                    '{{ info.used_count }}/{{ info.capacity }}'];
                var infoWindow = new AMap.InfoWindow({
                    content: content.join("<br>")  //传入 dom 对象，或者 html 字符串
                });
                infoWindow.open(map, ev.lnglat);
            });
            map.add(polyline);
        {% endfor %}
    {% endfor %}

    function show(flag) {
        if (flag == 1) {
            var rank = 'use';
        } else {
            var rank = 'available';
        }
        $.ajax({
            url: "{% url 'uccsit:use_rank' %}",
            data: {
                rank: rank,
                datetime: '{{ datetime }}',
            },
            cache: false,
            success: function (result) {
                use_rank = JSON.parse(result);
                var myItems = ["<div class=\"list-group\">"];
                all_block = 0;
                congestion_block = 0;
                underuse_block = 0;
                balance_block = 0;
                all_berth = 0;
                for (var i = 0; i < use_rank.length; i++) {
                    if (block_location[parseInt(use_rank[i].block_id)] == undefined) {
                        continue;
                    }
                    {# count data for dash #}
                    all_block += 1;
                    if (parseFloat(use_rank[i].occupancy_rate) > 0.85) {
                        congestion_block += 1;
                    } else if (parseFloat(use_rank[i].occupancy_rate) < 0.7) {
                        underuse_block += 1;
                    } else {
                        balance_block += 1;
                    }
                    all_berth += parseInt(use_rank[i].capacity)
                    {# count end #}
                    myItems.push(
                        "<a href=\"javascript:use_block_update_pic(" + use_rank[i].block_id + ',\'' + use_rank[i].road_name
                        + '\',\'' + use_rank[i].direction + '\',\'' + use_rank[i].left_or_right + "\')\" "
                        + "class=\"list-group-item list-group-item-action d-flex justify-content-between align-items-center\">"
                        + '<span><span class="font-weight-bold">' + use_rank[i].road_name + '</span><span class="font-weight-normal">'
                        + use_rank[i].direction + use_rank[i].left_or_right + '</span></span>' + '<span>'
                        + block_used[parseInt(use_rank[i].block_id)] + '/'
                        + block_capacity[parseInt(use_rank[i].block_id)] + '</span>'
                        + '<span class="badge badge-primary badge-pill">'
                        + use_rank[i].occupancy_rate + '</span>' + "</a>");
                }
                myItems.push('</div>');
                $("#sorted_occupancy").html('');
                $("#sorted_occupancy").append(myItems.join(""));
                show_dash();
                draw_sum_up_pie();
            },
        })
            .fail(function (xhr, status, errorThrown) {
                alert("Sorry, there was a problem!");
                console.log("Error: " + errorThrown);
                console.log("Status: " + status);
                console.dir(xhr);
            });
    }

    function use_block_update_pic(t_block_id, t_road_name, t_direction, t_left_or_right) {
        block_id = t_block_id;
        road_name = t_road_name;
        direction = t_direction;
        left_or_right = t_left_or_right;
        draw_block_vote(t_block_id, t_road_name, t_direction, t_left_or_right);
        draw_block_rate(block_scale);
        {# extra task: locate block been clicked #}
        if (block_location[t_block_id] == undefined) {
            alert('无位置信息');
        } else {
            map.panTo(block_location[t_block_id][1]);
            inner_text = '<p class="col text-center font-weight-bold" style="margin:0;">' + t_road_name + t_direction + t_left_or_right + '</p>'
            inner_text += '<br>容量: ' + block_capacity[t_block_id].toString()
                + ' 占用量: ' + block_used[t_block_id].toString()
            if (block_used[t_block_id] / block_capacity[t_block_id] > 0.85) {
                inner_text += '<span class="text-danger"> 占用率: '
                inner_text += (Math.round(block_used[t_block_id] / block_capacity[t_block_id] * 100)).toString() + '%</span><br>';
            } else if (block_used[t_block_id] / block_capacity[t_block_id] < 0.7) {
                inner_text += '<span class="text-primary"> 占用率: '
                inner_text += (Math.round(block_used[t_block_id] / block_capacity[t_block_id] * 100)).toString() + '%</span><br>';
            } else {
                inner_text += '<span class="text-warning"> 占用率: '
                inner_text += (Math.round(block_used[t_block_id] / block_capacity[t_block_id] * 100)).toString() + '%</span><br>';
            }
            var infoWindow = new AMap.InfoWindow({
                content: inner_text + '加载中...',  //传入 dom 对象，或者 html 字符串
            });
            infoWindow.open(map, block_location[t_block_id][1]);
            draw_parking_proportion(t_block_id, infoWindow, inner_text);
        }
    }

    function draw_block_vote(block_id, road_name, direction, left_or_right) {
        $.ajax({
            url: "{% url 'uccsit:block_vote' %}",
            data: {
                block_id: block_id,
                road_name: road_name,
                direction: direction,
                left_or_right: left_or_right,
                datetime: '{{ datetime }}',
                version: 'matplotlib'
            },
            success: function (result) {
                $("#canvas_block_bcu").html('');
                $("#canvas_block_bcu").append(result);
            }
        })
    }

    function hide_img() {
        $("#canvas_of_vote").html('');
    }

    function draw_aggregate_rates(data_scale) {
        console.log(data_scale);
        $.ajax({
            url: "{% url 'uccsit:aggregate_rates' %}",
            data: {
                datetime: '{{ datetime }}',
                data_scale: data_scale,
            },
            success: function (result) {
                $("#canvas_aggregate_rate").html('');
                $("#canvas_aggregate_rate").append(result);
            }
        })
    }

    function draw_block_rate(scale) {
        block_scale = scale
        console.log(scale);
        $.ajax({
            url: "{% url 'uccsit:block_rate' %}",
            data: {
                scale: block_scale,
                block_id: block_id,
                road_name: road_name,
                direction: direction,
                left_or_right: left_or_right,
                datetime: '{{ datetime }}',
                version: 'matplotlib'
            },
            success: function (result) {
                $("#canvas_block_rate").html('');
                $("#canvas_block_rate").append(result);
            }
        })
    }

    function draw_parking_proportion(block_id, infoWindow, inner_text) {
        $.ajax({
            url: "{% url 'uccsit:parking_proportion' %}",
            data: {
                block_id: block_id,
                datetime: '{{ datetime }}',
                capacity: block_capacity[block_id],
                occupied: block_used[block_id],
            },
            success: function (result) {
                infoWindow.close();
                infoWindow = new AMap.InfoWindow({
                    content: inner_text + result,  //传入 dom 对象，或者 html 字符串
                });
                infoWindow.open(map, block_location[block_id][1]);
            }
        })
    }

    function show_dash() {
        var content = '';
        content += '<h4 align="center">南山区' + all_block.toString() + '区块（' + all_berth.toString() + '泊位）总体状态</h4>';
        $('#summary-dash').html(content)
    }

    function draw_sum_up_pie() {
        $.ajax({
            url: "{% url 'uccsit:draw_sum_up_pie' %}",
            data: {
                all_block: all_block,
                congestion_block: congestion_block,
                underuse_block: underuse_block,
                balance_block: balance_block,
            },
            success: function (result) {
                $('#summary-pie').html(result)
            }
        })
    }

    {# Initialization #}
    show(1);
    draw_block_vote(35, '海德二道', '南侧', '靠右');
    draw_block_rate(block_scale);
    draw_aggregate_rates('week');
</script>